package org.wangblue.query;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.wangblue.common.Client;

import java.io.IOException;

/**
 * @Description: 分组查询
 * @Author: WangBlue
 * @Create: 2024-10-24 14:28
 * @Version: 1.0
 **/

public class GroupQuery {
    private static final String INDEX_NAME = "user";
    public static void main(String[] args) throws IOException {
        try (RestHighLevelClient client = Client.getClient()) {
            // 1. 创建搜索请求对象
            SearchRequest request = new SearchRequest();
            request.indices(INDEX_NAME);

            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.aggregation(AggregationBuilders.terms("age_groupby").field("age"));

            // 2. 设置请求体
            request.source(sourceBuilder);

            // 3. 客户端发送请求， 获取响应对象
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            // 4. 解析响应对象， 获取聚合结果
            Aggregations aggregations = response.getAggregations();
            if (aggregations != null) {
                Terms ageGroupby = aggregations.get("age_groupby");
                for(Terms.Bucket bucket : ageGroupby.getBuckets()) {
                    System.out.println("年龄: " + bucket.getKeyAsString() + " -> 文档数: " + bucket.getDocCount());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
